from typing import List, Generator
import io
import os
import tempfile
import logging
from contextlib import contextmanager

logger = logging.getLogger(__name__)

def validate_file_type(filename: str, allowed_types: List[str]) -> bool:
    """验证文件类型"""
    return any(filename.lower().endswith(ext) for ext in allowed_types)

def create_bytes_io() -> io.BytesIO:
    """创建一个字节流对象"""
    return io.BytesIO()

class TempFileManager:
    def __init__(self):
        self.temp_files: List[str] = []

    def create_temp_file(self, suffix: str = None) -> str:
        """创建临时文件并跟踪"""
        temp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
        self.temp_files.append(temp.name)
        return temp.name

    def cleanup(self):
        """清理所有临时文件"""
        for file_path in self.temp_files:
            try:
                if os.path.exists(file_path):
                    os.unlink(file_path)
                    logger.debug(f"已删除临时文件: {file_path}")
            except Exception as e:
                logger.error(f"删除临时文件失败 {file_path}: {str(e)}")
        self.temp_files.clear()

@contextmanager
def temp_file_manager() -> Generator[TempFileManager, None, None]:
    """临时文件管理器的上下文管理器"""
    manager = TempFileManager()
    try:
        yield manager
    finally:
        manager.cleanup() 